package com.liuhengjia.langchain4japply.api;

import dev.langchain4j.data.message.ImageContent;
import dev.langchain4j.data.message.TextContent;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatLanguageModel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Base64;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/image")
@RequiredArgsConstructor
public class ImageAPI {
    final ChatLanguageModel chatLanguageModel;

    @PostMapping("/low/chat")
    public String lowChat(@RequestParam(value = "message") String message,
                          @RequestParam(value = "file") MultipartFile file) {
        try {
            UserMessage userMessage = UserMessage.from(
                    TextContent.from(message),
                    ImageContent.from(Base64.getEncoder().encodeToString(file.getBytes()), MimeTypeUtils.IMAGE_JPEG_VALUE)
            );
            return chatLanguageModel.chat(List.of(userMessage)).aiMessage().text();
        } catch (IOException e) {
            log.error(e.getMessage());
            return "error";
        }
    }
}
